package mn.idax.exchange.otc.service.impl;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import mn.idax.exchange.common.CalendarUtil;
import mn.idax.exchange.otc.domain.BusinessApplyListResponse;
import mn.idax.exchange.otc.domain.BusinessConditionDTO;
import mn.idax.exchange.otc.entity.OTCBusinessApply;
import mn.idax.exchange.otc.entity.User;
import mn.idax.exchange.otc.enums.ApplyStateEnum;
import mn.idax.exchange.otc.enums.response.BusinessApplyResponseEnum;
import mn.idax.exchange.otc.exception.IdaxException;
import mn.idax.exchange.otc.mapper.GestureAuthenticationMapper;
import mn.idax.exchange.otc.mapper.OTCBusinessApplyMapper;
import mn.idax.exchange.otc.mapper.UserMapper;
import mn.idax.exchange.otc.service.BusinessApplyService;
import mn.idax.exchange.otc.util.DateUtils;
import mn.idax.exchange.otc.vo.PageVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

/***
 * 商户申请服务实现
 * @author .shohua
 * @time 2018.11.13
 */
@Service
public class BusinessApplyServiceImpl implements BusinessApplyService {

    @Autowired
    private OTCBusinessApplyMapper OTCBusinessApplyMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private GestureAuthenticationMapper gestureAuthenticationMapper;

    @Override
    public BusinessConditionDTO getBusinessCondition(int userId) {
        BusinessConditionDTO businessConditionDTO = new BusinessConditionDTO();

        Map<String, Integer> paramMap = Maps.newHashMap();
        paramMap.put("userId", userId);
        OTCBusinessApply businessApply = OTCBusinessApplyMapper.getBusinessApplyByMap(paramMap);
        if (businessApply == null) {
            businessConditionDTO.setStatus(ApplyStateEnum.noapply.getState());
        } else {
            businessConditionDTO.setStatus(businessApply.getStatus());
        }

        // 查询用户信息
        User user = userMapper.selectByPrimaryKey(userId);
        businessConditionDTO.setIsCertificate(user.getIscertificate());

        // 查询用户是高级认证
        paramMap.put("status", ApplyStateEnum.success.getState());
//        GestureAuthentication gestureAuthentication = gestureAuthenticationMapper.getGestureAuthenticationByMap(paramMap);
        businessConditionDTO.setIsGestureAuth(user.getIsadvancedcertificate());

        // TODO 冻结0.3个BTC 作为商家保证金，待确认需求

        return businessConditionDTO;
    }

    @Override
    public int submitApply(int userId) throws Exception {
        /** judge Qualifications 判断申请条件 **/
        // 获取用户资格
        BusinessConditionDTO businessCondition = getBusinessCondition(userId);
        if (!businessCondition.getIsCertificate()) {
            // 未通过实名认证
            throw new IdaxException(BusinessApplyResponseEnum.NO_CERTIFICATE.getCode());
        }
//        if (!businessCondition.getIsGestureAuth()) {
//            // 未通过手势认证
//            throw new IdaxException(BusinessApplyResponseEnum.NO_GESTUREAUTH.getCode());
//        }
        if (businessCondition.getStatus().equals(ApplyStateEnum.wait.getState())) {
            // 有未审核的申请
            throw new IdaxException(BusinessApplyResponseEnum.ALREADY_APPLY.getCode());
        }
        Map<String, Integer> paramMap = Maps.newHashMap();
        paramMap.put("userId", userId);
        // 查询是否有申请记录
        paramMap.put("status", ApplyStateEnum.success.getState());
        OTCBusinessApply businessApply = OTCBusinessApplyMapper.getBusinessApplyByMap(paramMap);
        if (null != businessApply) {
            // 有未审核的申请
            throw new IdaxException(BusinessApplyResponseEnum.ALREADY_BECOME.getCode());
        }

        // TODO 冻结0.3个BTC 作为商家保证金，待确认需求

        // 添加申请数据
        return OTCBusinessApplyMapper.insertBusinessApply(
                OTCBusinessApply.builder()
                        .userid(userId)
                        .status(ApplyStateEnum.wait.getState())
                        .createtime(CalendarUtil.getUTCDate().getTime())
                        .updatetime(CalendarUtil.getUTCDate().getTime())
                        .build()
        );
    }

    @Override
    public PageVo<BusinessApplyListResponse> getBusinessListByUserId(Map<String, Integer> paramMap) {
        List<BusinessApplyListResponse> respList = Lists.newArrayList();
        List<OTCBusinessApply> otcBusinessApplies = OTCBusinessApplyMapper.listBusinessApplyPage(paramMap);

        for (OTCBusinessApply otcBusinessApply : otcBusinessApplies) {
            BusinessApplyListResponse businessApplyListResponse = new BusinessApplyListResponse();
            BeanUtils.copyProperties(otcBusinessApply, businessApplyListResponse);
            businessApplyListResponse.setCreatetime(DateUtils.getDateToStr(otcBusinessApply.getCreatetime(),"yyyy-MM-dd'T'HH:mm:ss"));
            businessApplyListResponse.setUpdatetime(DateUtils.getDateToStr(otcBusinessApply.getUpdatetime(),"yyyy-MM-dd'T'HH:mm:ss"));
            respList.add(businessApplyListResponse);
        }
        return PageVo.<BusinessApplyListResponse>builder()
                .data(respList)
                .pageIndex(paramMap.get("pageIndex"))
                .totalRecord(OTCBusinessApplyMapper.listBusinessApplyTotal(paramMap.get("userId")))
                .build();
    }

    @Override
    public Integer isbusinesser(Integer userId) {
        return OTCBusinessApplyMapper.isBusinesser(userId);
    }
}
